/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hhf.jmx;

import hhf.logger.LoggerName;
import java.lang.management.ManagementFactory;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.slf4j.Logger;

/**
 *
 * @author François
 */
@JMXManaged
@Interceptor
public class JMXRegister {

	@Inject
	@LoggerName("JMX")
	Logger logger;
	private MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

	@Resource(lookup = "java:app/AppName")
	private String appName;

	
	@PostConstruct
	public void record(InvocationContext ic) throws Exception {
		Object obj = ic.getTarget();
		Class interfs[] = obj.getClass().getInterfaces();
		for(Class interf : interfs) {
			if(interf.getSimpleName().endsWith("MBean") || interf.getSimpleName().endsWith("MXBean")) {
				String mBeanName = appName+":type=" + interf.getSimpleName();
				logger.info("Registration of "+mBeanName);
				try {
					ObjectName objectName = new ObjectName(mBeanName);
					Object annoted = new AnnotatedStandardMBean(obj, interf);
					mbs.registerMBean(annoted, objectName);
				} catch (Exception e) {
					throw new IllegalStateException("Problem during registration of MBean : " + mBeanName, e);
				}
			}
		}
	}

	@PreDestroy
	public void unregisterFromJMX(InvocationContext ic) {
		Object obj = ic.getTarget();
		Class interfs[] = obj.getClass().getInterfaces();
		for(Class interf : interfs) {
			if(interf.getSimpleName().endsWith("MBean") || interf.getSimpleName().endsWith("MXBean")) {
				String mBeanName = appName+":type=" + interf.getSimpleName();
				logger.info("Unregistration of "+mBeanName);
				try {
					ObjectName objectName = new ObjectName(mBeanName);
					mbs.unregisterMBean(objectName);
				} catch (Exception e) {
					throw new IllegalStateException("Problem during unregistration of MBean : " + mBeanName, e);
				}
			}
		}
	}
}
